package com.common.www.service;

import org.springframework.boot.base.jpa.service.BaseService;
import com.common.www.bean.entity.TestDatabase;
import com.common.www.redis.lock.LockUtil;
import com.common.www.repository.TestDatabaseRepository;
import com.common.www.service.auth.UserService;
import com.common.www.utils.TxtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

import static com.common.www.redis.lock.LockName.TEST_QIANGGOU;


/**
 * Created by cwx183898 on 2017/12/14.
 */
@Service
@Transactional
public class TestDatabaseService extends BaseService<TestDatabase, Long> {
    @Autowired
    private TestDatabaseRepository repository;
    @Autowired
    UserService userService;

    @Override
    public TestDatabaseRepository getRepository() {
        return repository;
    }

    public void update() {
        repository.updateStateByMoney(1L);
    }

    public void qianggou(Long id) {
        //以下为抢锁的代码
        try {
            boolean getLock = LockUtil.tryLock(TEST_QIANGGOU.toString() + id, 10, 5, TimeUnit.SECONDS);
            if (!getLock) {//未抢到
                return;
            }
            TestDatabase testDatabase = findOne(TxtUtil.getLong(id + ""));
            if (testDatabase.getInventory() <= 0) {
                return;
            }
            testDatabase.setInventory(testDatabase.getInventory() - 1);
            save(testDatabase);
            LockUtil.unlock(TEST_QIANGGOU.toString() + id);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void addQianggou(Long id) {
        //以下为抢锁的代码
        try {
            boolean getLock = LockUtil.tryLock(TEST_QIANGGOU.toString() + id, 10, 5, TimeUnit.SECONDS);
            if (!getLock) {//未抢到
                return;
            }
            TestDatabase testDatabase = findOne(TxtUtil.getLong(id + ""));
            if (testDatabase.getInventory() <= 0) {
                return;
            }
            testDatabase.setInventory(testDatabase.getInventory() + 1);
            save(testDatabase);
            LockUtil.unlock(TEST_QIANGGOU.toString() + id);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
